<template>
  <div class="main">
    <div class="air-column">
      <h2>剩机人</h2>
      <el-form
        ref="usersForm"
        class="member-info"
        :model="{
          users: users,
        }"
      >
        <div
          class="member-info-item"
          v-for="(user, index) in users"
          :key="index"
        >
          <el-form-item
            label="乘机人类型"
            :prop="`users[${index}].username`"
            :rules="[
              {
                required: true,
                message: '请输入数据',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="user.username"
              placeholder="乘机人姓名"
              class="input-with-select"
            >
            </el-input>
          </el-form-item>

          <el-form-item
            label="证件类型"
            :prop="`users[${index}].id`"
            :rules="[
              {
                required: true,
                message: '请输入数据',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="user.id"
              placeholder="身份证号码"
              class="input-with-select"
            >
            </el-input>
          </el-form-item>

          <span class="delete-user" @click="handleDeleteUser(index)">-</span>
        </div>
      </el-form>

      <el-button class="add-member" type="primary" @click="handleAddUsers"
        >添加乘机人</el-button
      >
    </div>

    <div class="air-column">
      <h2>保险</h2>
      <div>
        <el-checkbox-group v-model="insurances">
          <div
            class="insurance-item"
            v-for="item in data.insurances"
            :key="item.id"
          >
            <el-checkbox :label="item.id" border>
              {{
                `${item.type}: ¥ ${item.price} /份 x ${users.length} 最高赔付 ${item.compensation}`
              }}
            </el-checkbox>
          </div>
        </el-checkbox-group>
        <h2>发票</h2>
        <div>
          <el-checkbox v-model="invoice">需要发票</el-checkbox>
        </div>
      </div>
    </div>

    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form
          label-width="80px"
          :model="{
            contactName,
            contactPhone,
            captcha,
          }"
          :rules="contactRules"
          ref="contactForm"
        >
          <el-form-item label="姓名" prop="contactName">
            <el-input v-model="contactName"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="contactPhone">
            <el-input placeholder="请输入内容" v-model="contactPhone">
              <template slot="append">
                <el-button @click="handleSendCaptcha">发送验证码</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="captcha"></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="warning"
          class="submit"
          @click="handleSubmit"
          v-if="$store.state.user.userInfo.token"
          >提交订单</el-button
        >

        <div v-else class="container">
          <!-- 主要内容 -->
          <el-row type="flex" justify="center" align="middle" class="main">
            <div class="form-wrapper">
              <!-- 表单头部tab -->
              <el-row type="flex" justify="center" class="tabs">
                <span
                  :class="{ active: currentTab === index }"
                  v-for="(item, index) in [`登录`, `注册`]"
                  :key="index"
                  @click="handleChangeTab(index)"
                >
                  {{ item }}
                </span>
              </el-row>

              <!-- 登录功能组件 -->
              <LoginForm v-if="currentTab == 0" />

              <!-- 注册功能组件 -->
              <RegisterForm v-if="currentTab == 1" />
            </div>
          </el-row>
        </div>
      </div>
    </div>
    <div style="display: none">
      {{ totalPrice }}
    </div>
  </div>
</template>

<script>
import LoginForm from "../../components/user/LoginFrom";
import RegisterForm from "../../components/user/RegisterFrom";
export default {
  data() {
    return {
      currentTab: 0,
      contactRules: {
        contactName: [
          {
            required: true,
            message: "请输入数据",
            trigger: "blur",
          },
        ],

        contactPhone: [
          {
            required: true,
            message: "请输入数据",
            trigger: "blur",
          },
        ],
        captcha: [
          {
            required: true,
            message: "请输入数据",
            trigger: "blur",
          },
        ],
      },
      users: [
        {
          username: "幡儿",
          id: "44145884662512354",
        },
      ],
      insurances: [],
      contactName: "范儿",
      contactPhone: "17715425136",
      captcha: "000000",
      invoice: false,
    };
  },
  props: ["data"],
  // watch: {
  //   users: {
  //     handler() {
  //       this.getTotalPrice();
  //     },
  //     immediate: true,
  //   },
  //   insurances: {
  //     handler() {
  //       this.getTotalPrice();
  //     },
  //     immediate: true,
  //   },
  // },
  components: {
    LoginForm,
    RegisterForm,
  },

  computed: {
    totalPrice() {
      const ticketPrice = this.data.base_price * this.users.length;
      let insurancePrice = 0;

      // 现在选中的checkList 应该是 this.insurances 格式类似 [1,2]
      // 遍历里面的每个被选中的id
      this.insurances.forEach((id) => {
        // 遍历到的每个元素都是 id 如 1 或者 2
        // 需要在整个保险数据中找出对应id的价格
        // 保险对象在 this.data.insurances
        // 结构大概是一个数组包裹保险数据对象
        // [
        //     {
        //         id: 1,
        //         price: 998
        //     }
        // ]
        // 遍历这个数组, 找出对应 id 的价格
        // 可以根据选中保险 id 计算出当前保险应该付多少钱的函数
        insurancePrice += this.getInsurancePrice(id);
      });

      // this.insurances.forEach(element => {
      //     // [1,2]
      //     // 遍历选中的保险, 这里选中时的储存都是保险id
      //     console.log(element);
      //     // 拿到了id以后应该根据这个id获取保险的价格
      //     this.data.insurances.forEach(insurance => {
      //         if (insurance.id == element) {
      //             // 拿到了当前选中 id 保险的价格,
      //             // 应该乘以人数, 添加到总价上
      //             insurancePrice += insurance.price * this.users.length
      //         }
      //     });
      // });

      console.log(insurancePrice);
      const totalPrice = ticketPrice + insurancePrice;
      // 得出了总价
      this.$emit("setTotalPrice", totalPrice);
      console.log("计算总价" + totalPrice);
      return totalPrice;
    },
  },
  methods: {
    handleChangeTab(index) {
      this.currentTab = index;
    },
    getInsurancePrice(id) {
      // 可以根据选中保险 id 计算出当前保险应该付多少钱的函数
      let res = 0;
      this.data.insurances.forEach((element) => {
        if (id == element.id) {
          res = element.price * this.users.length;
        }
      });
      return res;
    },
    // 添加乘机人
    handleAddUsers() {
      this.users.push({
        username: "",
        id: "",
      });
    },

    // 移除乘机人
    handleDeleteUser(index) {
      this.users.splice(index, 1);
    },

    // 发送手机验证码
    handleSendCaptcha() {
      if (!this.contactPhone) {
        this.$message.error("请输入手机号");
        return;
      }
      this.$axios({
        method: "post",
        url: "/captchas",
        data: {
          tel: this.contactPhone,
        },
      }).then((res) => {
        console.log(res.data);
        if (res.data.code) {
          this.$message.success("发送成功" + res.data.code);
        }
      });
    },

    // 提交订单 // 异步函数写成同步的样子
    async handleSubmit() {
      console.log("点击按钮提交");
      const [validUsers, validContact] = await Promise.all([
        this.$refs.usersForm.validate(),
        this.$refs.contactForm.validate(),
      ]);
      if (validUsers && validContact) {
        this.sendRequest();
        date;
      }
    },

    sendRequest() {
      console.log(this.users);
      //拼接数据
      const data = {
        users: this.users,
        insurances: this.insurances,
        contactName: this.contactName,
        contactPhone: this.contactPhone,
        invoice: this.invoice,
        seat_xid: this.$route.query.seat_xid,
        air: this.$route.query.id,
        captcha: this.captcha,
      };

      this.$axios({
        method: "post",
        url: "/airorders",
        headers: {
          Authorization: "Bearer " + this.$store.state.user.userInfo.token,
        },
        data,
      }).then((res) => {
        console.log(res.data);
        this.$router.push("/air/pay?id=" + res.data.data.id);
      });
    },
  },
};
</script>

<style scoped lang="less">
.air-column {
  border-bottom: 1px #ddd dashed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.air-column h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}

/deep/ .el-select .el-input {
  width: 130px;
}

.input-with-select {
  width: 590px;
}

.input-with-select /deep/ .el-input-group__prepend {
  background-color: #fff;
}
// .member-info /deep/ .el-form-item {
//   margin-bottom: 0;
// }

.member-info-item {
  border-bottom: 1px #eee dashed;
  padding-bottom: 20px;
  position: relative;

  &:first-child {
    .delete-user {
      display: none;
    }
  }
}

.add-member {
  margin-top: 20px;
}

.delete-user {
  display: block;
  background: #ddd;
  width: 16px;
  height: 16px;
  font-size: 14px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  cursor: pointer;
  border-radius: 50px;
  position: absolute;
  right: -30px;
  top: 50%;
}

.insurance {
  > div {
    margin-top: 10px;
  }
}

.insurance-item {
  margin-bottom: 20px;
}

.contact {
  /deep/ .el-input {
    width: 50%;
  }
}

.submit {
  margin: 50px auto;
  display: block;
  width: 250px;
  height: 50px;
}
.container {
  .main {
    height: 100%;
    margin: 0 auto;
    position: relative;

    .form-wrapper {
      width: 400px;
      margin: 0 auto;
      background: #fff;
      box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.1);
      overflow: hidden;
      /deep/ .el-input {
        width: 100%;
      }

      .tabs {
        span {
          display: block;
          width: 50%;
          height: 50px;
          box-sizing: border-box;
          border-top: 2px #eee solid;
          background: #eee;
          line-height: 48px;
          text-align: center;
          cursor: pointer;
          color: #666;

          &.active {
            color: orange;
            border-top-color: orange;
            background: #fff;
            font-weight: bold;
          }
        }
      }
    }
  }
}
</style>